package com.jike.mahjong.common.filter;

import javax.servlet.*;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;

/**
 * Created by star on 2016/9/28.
 */
public class VisitfFilter implements Filter {
    protected FilterConfig config = null;

    public void init(FilterConfig filterConfig) throws ServletException {
        this.config = config;
    }

    /**
     * 过滤选项，判断用户是否登录，禁止非法访问平台
     *
     * @param servletRequest
     * @param servletResponse
     * @param chain
     * @throws IOException
     * @throws ServletException
     */
    public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain chain) throws IOException, ServletException {
        HttpServletRequest request = (HttpServletRequest) servletRequest;
        HttpSession session = request.getSession();
        String uriPath = request.getRequestURI();

        // 不需要过滤的页面
        List<String> list = new ArrayList<String>();
        list.add("/views/login.jsp");
        list.add("/user/login.html");
        list.add("/agent/login.html");
/*        list.add("/user/login.html");
        list.add("/agent/login.html");*/
        list.add("/views/agentlogin.jsp");
        list.add("/views/index.jsp");
        if (!list.contains(uriPath) && !uriPath.contains("login")) {
            String name = (String) session.getAttribute("loginUserName");
            if (session == null || session.getAttribute("loginUserName") == null) {
                System.out.println("session失效! 跳转到登陆页面...");
                // 分发到登陆页面
                HttpServletResponse rs = (HttpServletResponse) servletResponse;
                String path = request.getContextPath();
                rs.sendRedirect(path + "/user/login.html");
                return;
            } else {
                String userId = String.valueOf(session.getAttribute("s_user_id"));
                System.out.println("session : s_user_id =" + userId);
                System.out.println("session有效...");
            }
        }
        chain.doFilter(servletRequest, servletResponse);
    }

    public void destroy() {
        this.config = null;
    }
}
